<template>
  <n-drawer
    v-model:show="modelValue.toEdit"
    :width="502"
    :height="500"
    :placement="'bottom'"
  >
    <n-drawer-content
      :title="toADDFlag ? '添加' : '修改'"
      closable
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        :size="'medium'"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        :style="{
          maxWidth: '640px',
        }"
      >
        <n-form-item
          label="名字"
          path="name"
        >
          <n-input
            v-model:value="formValue.name"
            placeholder="输入名字"
          />
        </n-form-item>
        <n-form-item
          label="描述"
          path="desc"
        >
          <n-input
            v-model:value="formValue.desc"
            placeholder="输入描述"
          />
        </n-form-item>
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick"
          >
            {{ toADDFlag ? "添加" : "修改" }}
          </n-button>
        </n-form-item>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup generic="T extends object & { toEdit: boolean,toDelete:boolean,toDealRowId: number|undefined}">
import { LifeModelData } from "@model/lifeModel";
import UseLifeModel from "@pinias/UseLifeModel";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import pinia from "@pinias/pinia";
import { NForm, NFormItem, NInput, NDrawer, NDrawerContent, NButton, FormInst, useMessage } from "naive-ui";
import { ref, computed, watch } from "vue";

const message = useMessage();
// 全局数据
const { getLifeModel } = UseLifeModel(pinia);
const lifeModel = getLifeModel();
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting = getSurfaceSetting();
// 父组件数据
const props = defineProps<{ modelValue: T }>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});

// 页面数据
const toADDFlag = computed(() => {
  return typeof modelValue.value.toDealRowId == "undefined";
});
const rules = {
  name: {
    required: true,
    message: "请输入名字",
    trigger: ["input"],
  },
  phone: {
    required: true,
    message: "请输入描述",
    trigger: ["input"],
  },
};
const formRef = ref<FormInst | null>(null);
const getNewFormValue = () => {
  const nullModel = {
    id: surfaceSetting.maxId,
    name: "",
    desc: "",
  };
  if (toADDFlag.value) return nullModel;
  else {
    const toDealRow = lifeModel.getLifeModelDataById(modelValue.value.toDealRowId);
    if (toDealRow === undefined) {
      return nullModel;
    } else
      return {
        id: toDealRow.id,
        name: toDealRow.name,
        desc: toDealRow.desc,
      };
  }
};

const formValue = ref(getNewFormValue());
watch(
  //也可以第一参数为响应式数据
  modelValue.value,
  () => {
    formValue.value = getNewFormValue();
  },
);

// 表单提交:添加/编辑逻辑
const addNewLifeModel = () => {
  // console.log('toDealRow',toDealRow)
  // console.log('formValue',formValue)
  const tosave = formValue.value;
  /// console.log('addNewLifeModel',lifeModel.data,tosave)
  if (toADDFlag.value) {
    lifeModel.list.push(tosave.id);
    lifeModel.data.push(new LifeModelData(tosave.id, tosave.name, tosave.desc, []));
    surfaceSetting.maxId++;
    // formValue.value = getNewFormValue();
  } else {
    const temp = lifeModel.getLifeModelDataById(tosave.id);
    if (temp != undefined) {
      temp.name = tosave.name;
      temp.desc = tosave.desc;
    }
  }
  surfaceSetting.LifeModelListKey = new Date().getTime();
  // formValue = getNewFormValue();
};
const handleValidateClick = (e: MouseEvent) => {
  //console.log('toDealRow',toDealRow);
  e.preventDefault();
  formRef.value?.validate((errors: any) => {
    if (!errors) {
      addNewLifeModel();
      modelValue.value.toEdit = false;
      message.success("保存成功");
    } else {
      message.error("保存失败");
    }
  });
};
</script>
